package com.xiaohei.crm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaohei.crm.common.exception.XiaoheiException;
import com.xiaohei.crm.common.result.Result;
import com.xiaohei.crm.dao.Orders;
import com.xiaohei.crm.mapper.OrdersMapper;
import com.xiaohei.crm.service.OrdersService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.xiaohei.crm.common.RedisEnums.ORDERS_UPDATE_LOCK;
import static com.xiaohei.crm.common.RedisEnums.ORDER_REGISTRY_KEY;
import static com.xiaohei.crm.common.result.ResultCodeEnum.DATA_ERROR;

/**
 * ClassName: OrdersServiceImpl
 * Package:
 * Description:
 *
 * @Author:xiaohei
 * @Create 2024/6/24 8:37
 * Version 1.0
 */
@Service
@RequiredArgsConstructor
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    private final OrdersMapper ordersMapper;
    private final StringRedisTemplate stringRedisTemplate;
    private final RedissonClient redissonClient;

    @Override
    public Result<IPage> findByPage() {
        Page<Orders> page = new Page<>();
        LambdaQueryWrapper<Orders> eq = Wrappers.lambdaQuery(Orders.class).eq(Orders::getDelFlag, 0);
        return Result.ok(ordersMapper.selectPage(page, eq));
    }

    @Override
    public void saveOrders(Orders orders) {
        List<String> range = stringRedisTemplate
                .opsForList().range(ORDER_REGISTRY_KEY + orders.getId(), 0, -1);
        if (!CollectionUtil.isEmpty(range)) {
            throw new XiaoheiException(DATA_ERROR);
        }


        orders.setId(orders.getCustomerId().toString() + System.currentTimeMillis());
        int isInsert = ordersMapper.insert(orders);
        if (isInsert < 1) {
            throw new XiaoheiException(DATA_ERROR);
        }
        stringRedisTemplate.opsForList()
                .leftPushAll(ORDER_REGISTRY_KEY + orders.getId(), orders.getId(), orders.getOrderStatus().toString());

    }

    @Override
    public void updateOrdersById(Orders orders) {
        RLock lock = redissonClient.getLock(ORDERS_UPDATE_LOCK + orders.getId());
        lock.lock();
        try {
            List<String> range = stringRedisTemplate.opsForList().range(ORDER_REGISTRY_KEY + orders.getId(), 0, -1);
            if (CollectionUtil.isEmpty(range)) {
                throw new XiaoheiException(DATA_ERROR);
            }

            LambdaQueryWrapper<Orders> eq =
                    Wrappers.lambdaQuery(Orders.class).eq(Orders::getId, orders.getId());
            int update = baseMapper.update(orders, eq);
            if(update < 1){
                throw new XiaoheiException(DATA_ERROR);
            }
            stringRedisTemplate.opsForList().set(ORDER_REGISTRY_KEY + orders.getId(),1,orders.getOrderStatus().toString());
        }catch (Throwable e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    @Override
    public void removeByOrdersId(String id) {
        List<String> range = stringRedisTemplate.opsForList().range(ORDER_REGISTRY_KEY + id, 0, -1);
        if (CollectionUtil.isEmpty(range)) {
            throw new XiaoheiException(DATA_ERROR);
        }

        LambdaUpdateWrapper<Orders> updateWrapper =
                Wrappers.lambdaUpdate(Orders.class).eq(Orders::getOrderStatus,4).eq(Orders::getId, id);
        Orders orders = Orders.builder().delFlag(1).build();
        int update = baseMapper.update(orders, updateWrapper);
        if(update < 1){
            throw new XiaoheiException(DATA_ERROR);
        }
        stringRedisTemplate.delete(ORDER_REGISTRY_KEY + id);
    }

}
